import axios from 'axios'
import { getToken } from './getToken'
import store from '@/store/index'
import router from '@/router/index'

const request = axios.create({
  timeout: 30000,
  baseURL: 'http://localhost:3000'
})

// 设置请求拦截器添加 access_token
request.interceptors.request.use((option) => {
  const token = getToken()
  option.method = option.method.toLowerCase()
  if (option.method === 'post') {
    option.data.access_token = token
  } else {
    if (option.params) {
      option.params.access_token = token
    } else {
      option.params = {}
      option.params.access_token = token
    }
  }
  return option
})

// 设置相应拦截器防止 token 过期
request.interceptors.response.use(async (option) => {
  // 如果登录过期了
  if (option.data.errcode === 42001) {
    // 1. 重新发送登录请求
    const { data } = await request({
      method: 'POST',
      url: '/login',
      data: {
        appid: window.localStorage.getItem('appid'),
        secret: window.localStorage.getItem('secret'),
        grant_type: 'client_credential'
      }
    })
    // 2. 将本地数据更新
    if (data.access_token) {
      store.commit('changeToken', data.access_token)
      // 3. 重新发送之前的请求
      const oldOption = {
        method: option.config.method,
        url: option.config.url
      }
      if (oldOption.method.toLowerCase() === 'post') {
        oldOption.data = option.config.data
      } else {
        oldOption.params = option.config.params
      }
      await request(oldOption)
    }
  }
  // 非法身份
  if (option.data.errcode === 40001) {
    router.push({
      name: 'login'
    })
  }
  return option
})

export default request
